from CvPythonExtensions import *
# is this currently needed?
import CvScreenEnums
import CvUtil
import Popup as PyPopup
import PyHelpers
import TradeUtil

# globals
gc = CyGlobalContext()
localText = CyTranslator()
PyPlayer = PyHelpers.PyPlayer

class CustomFunctions:

	def getUnitIcon(self, iUnit):
		if iUnit == gc.getInfoTypeForString('UNIT_DOCTOR'):
			return u"%c" % CyGame().getSymbolID(FontSymbols.HEALTHY_CHAR)
		elif iUnit == gc.getInfoTypeForString('UNIT_CHAPLAIN'):
			return u"%c" %(gc.getCommerceInfo(CommerceTypes.COMMERCE_CULTURE).getChar())
		elif iUnit == gc.getInfoTypeForString('UNIT_TRANSCEND'):
			return u"%c" % unichr(CyGame().getSymbolID(FontSymbols.POWER_CHAR) + 8)
		elif iUnit == gc.getInfoTypeForString('UNIT_DATAJACK'):
			return u"%c" %(gc.getCommerceInfo(CommerceTypes.COMMERCE_ESPIONAGE).getChar())
		elif iUnit == gc.getInfoTypeForString('UNIT_SCIENTIST'):
			return u"%c" %(gc.getCommerceInfo(CommerceTypes.COMMERCE_RESEARCH).getChar())
		elif iUnit == gc.getInfoTypeForString('UNIT_TYCOON'):
			return u"%c" %(gc.getCommerceInfo(CommerceTypes.COMMERCE_GOLD).getChar())
		elif iUnit == gc.getInfoTypeForString('UNIT_ENGINEER'):
			return u"%c" %(gc.getYieldInfo(YieldTypes.YIELD_PRODUCTION).getChar())
		elif iUnit == gc.getInfoTypeForString('UNIT_GENERAL'):
			return u"%c" % CyGame().getSymbolID(FontSymbols.STRENGTH_CHAR)

	def calcPercentages(self, pPlayer):
		# Calc total rate
		iTotal = 0
		for iUnit in range(gc.getNumUnitInfos()):
			iTotal += pPlayer.getGreatPeopleUnitProgress(iUnit)
	
		# Calc individual percentages based on rates and total
		percents = []
		if (iTotal > 0):
			iLeftover = 100
			for iUnit in range(gc.getNumUnitInfos()):
				iProgress = pPlayer.getGreatPeopleUnitProgress(iUnit)
				if (iProgress > 0):
					iPercent = 100 * iProgress / iTotal
					iLeftover -= iPercent
					percents.append((iPercent, iUnit))
			# Add remaining from 100 to first in list to match Civ4
			if (iLeftover > 0):
				percents[0] = (percents[0][0] + iLeftover, percents[0][1])
		return percents

	def getGreatPeopleText(self, pPlayer, iGPTurns, iGPBarWidth):
		sGreatPeopleChar = u"%c" % CyGame().getSymbolID(FontSymbols.GREAT_PEOPLE_CHAR)
		lPercents = self.calcPercentages(pPlayer)
		if (len(lPercents) == 0):
			if (iGPTurns):
				szText = localText.getText("INTERFACE_GREAT_PERSON_TURNS", (sGreatPeopleChar, iGPTurns))
			else:
				szText = sGreatPeopleChar
		else:
			lPercents.sort(reverse=True)
			if (len(lPercents) == 1):
				iPercent, iUnit = lPercents[0]
				pInfo = gc.getUnitInfo(iUnit)
				if (iGPTurns):
					szText = localText.getText("INTERFACE_GREAT_PERSON_TURNS", (pInfo.getDescription(), iGPTurns))
				else:
					szText = unicode(pInfo.getDescription())
			else:
				if (iGPTurns):
					szText = localText.getText("INTERFACE_GREAT_PERSON_TURNS", (sGreatPeopleChar, iGPTurns))
				else:
					szText = sGreatPeopleChar + u":"
				szTypes = ""
				for iPercent, iUnit in lPercents:
					szNewTypes = szTypes + u" %c%d%%" % (self.getUnitIcon(iUnit), iPercent)
					szNewText = szText + u"<font=2> -%s</font>" % szTypes
					if (CyInterface().determineWidth(szNewText) > iGPBarWidth - 10):
						# Keep under width
						break
					szTypes = szNewTypes
				if (len(szTypes) > 0):
					szText += u"<font=2> -%s</font>" % szTypes
		return szText
	
	def getTechTrades(self, player, team):
		iPlayerID = player.getID()
		tradeData = TradeData()
		tradeData.ItemType = TradeableItems.TRADE_TECHNOLOGIES
		techsByPlayer = {}
		for loopPlayer in TradeUtil.getTechTradePartners(player):
			techsToTrade = set()
			for iLoopTech in range(gc.getNumTechInfos()):
				tradeData.iData = iLoopTech
				if (loopPlayer.canTradeItem(iPlayerID, tradeData, False)):
					if (loopPlayer.getTradeDenial(iPlayerID, tradeData) == DenialTypes.NO_DENIAL): # will trade
						techsToTrade.add(iLoopTech)
			techsByPlayer[loopPlayer.getID()] = techsToTrade
		return techsByPlayer
		
	## Displaying Alert Messages

	def addMessageNoIcon(self, iPlayer, message):
		"Displays an on-screen message with no popup icon."
		self.addMessage(iPlayer, message, None)

	def addMessageAtCity(self, iPlayer, message, icon, city):
		"Displays an on-screen message with a popup icon that zooms to the given city."
		self.addMessage(iPlayer, message, icon, city.getX(), city.getY(), True, True)

	def addMessageAtPlot(self, iPlayer, message, icon, plot):
		"Displays an on-screen message with a popup icon that zooms to the given plot."
		self.addMessage(iPlayer, message, icon, plot.getX(), plot.getY(), True, True)

	def addMessage(self, iPlayer, szString, szIcon, iFlashX=-1, iFlashY=-1, bOffArrow=False, bOnArrow=False):
		"Displays an on-screen message."
		"""
		Make these alerts optionally show a delayable popup with various options.
		a) show: 
		
		Happy: Zoom to City, Turn OFF avoid growth, Whip (maybe?), Ignore
		Unhappy:  Zoom to City, Turn on Avoid Growth, Suggest cheapest military unit (with right civic), Open Resources screen in FA, Ignore. (for future = suggest building)
		
		Healthy: Zoom to City, Turn OFF avoid growth, Ignore
		Unhealthy:  Zoom to City, Turn on Avoid Growth, Whip population, Open Resources screen in FA, Ignore. (for future = suggest building)
		
		Growth: Zoom to City, Turn on avoid Growth, Whip, Ignore
		Starvation: Zoom to City, Turn on avoid Growth, Ignore
		
		Culture:  Zoom to City, Ignore
		"""
		eventMessageTimeLong = gc.getDefineINT("EVENT_MESSAGE_TIME_LONG")
		CyInterface().addMessage(iPlayer, True, eventMessageTimeLong,
								 szString, None, InterfaceMessageTypes.MESSAGE_TYPE_INFO, 
								 szIcon, ColorTypes(-1),
								 iFlashX, iFlashY, bOffArrow, bOnArrow)
								 
	def buildTechString(self, techs):
		return self.buildItemString(techs, gc.getTechInfo, CvTechInfo.getDescription)
		
	def buildItemString(self, items, getItemFunc, getNameFunc):
		names = [getNameFunc(getItemFunc(eItem)) for eItem in items]
		names.sort()
		return u", ".join(names)